import React, { useReducer } from "react"

interface TodoItem {
    id: number
    text: string
}

interface TodoListState {
    todos: TodoItem[]
}

type TodoAction =
    | { type: 'ADD_TODO', payload: { text: string } }
    | { type: 'REMOVE_TODO', payload: { id: number } }

const initState: TodoListState = {
    todos: []
}

const todoReducer = (state: TodoListState, action: TodoAction): TodoListState => {
    switch (action.type) {
        case 'ADD_TODO':
            return {
                todos: [...state.todos, { id: Date.now(), text: action.payload.text }]
            }

        case 'REMOVE_TODO':
            return {
                todos: state.todos.filter(todo => todo.id !== action.payload.id)
            }
        default:
            throw Error('unknown type')
    }
    return state
}

export default function TodoList() {
    const [state, dispatch] = useReducer(todoReducer, initState)

    const addTodo = (text: string) => {
        dispatch({ type: 'ADD_TODO', payload: { text } })
    }

    const removeTodo = (id: number) => {
        dispatch({ type: 'REMOVE_TODO', payload: { id } })
    }

    const ulStyle: React.CSSProperties = {
        listStyleType: "none",
        padding: "0px",
        margin: '0px'
    }

    return (
        <div>
            <h2>Todo List</h2>
            <ul style={ulStyle}>
                {state.todos.map(todo => (
                    <li key={todo.id}>
                        {todo.text}
                        <button onClick={() => removeTodo(todo.id)}>Remove</button>
                    </li>
                ))}
            </ul>
            <input
                type="text"
                placeholder="Add a new todo"
                onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
                    if (e.key === 'Enter') {
                        addTodo(e.currentTarget.value)
                        e.currentTarget.value = ''
                    }
                }}
            />
        </div>
    )
}